<template>
  <div class="playwright-page">
    <div class="header">
      <h2>AI自动化测试系统</h2>
      <div class="search-bar">
        <input type="text" placeholder="搜索测试用例..." v-model="searchQuery">
        <button @click="searchTestCases"><i class="fas fa-search"></i></button>
      </div>
    </div>
    
    <div class="file-selection">
      <div class="file-input-container">
        <label for="file-upload">选择测试文件:</label>
        <input 
          type="file" 
          id="file-upload" 
          @change="handleFileSelect"
          class="file-input"
        >
        <span class="file-name">{{ selectedFile ? selectedFile.name : '未选择文件' }}</span>
      </div>
      
      <div class="folder-input-container">
        <label for="folder-upload">选择测试文件夹:</label>
        <input 
          type="file" 
          id="folder-upload" 
          webkitdirectory 
          directory 
          @change="handleFolderSelect"
          class="file-input"
        >
        <span class="file-name">{{ selectedFolder ? `${selectedFolder.files.length} 个文件` : '未选择文件夹' }}</span>
      </div>
    </div>
    
    <ApiKeyInput 
      :apiKey="apiKey"
      @update:apiKey="updateApiKey"
      @save="saveApiKey"
    />
    
    <div class="card-grid">
      <TestCaseCard 
        title="页面结构分析"
        icon="sitemap"
        :features="[
          '识别所有可交互元素（按钮、链接、表单）',
          '提取元素属性（ID、类名、文本内容）',
          '构建页面元素关系图谱',
          '检测潜在可访问性问题'
        ]"
      />
      
      <TestCaseCard 
        title="AI 用例生成"
        icon="brain"
        :features="[
          '核心功能测试用例',
          '边界值和异常场景',
          '用户旅程测试',
          '跨浏览器兼容性测试'
        ]"
      />
      
      <TestCaseCard 
        title="Playwright 脚本生成"
        icon="code"
        :features="[
          '自动生成定位器（智能选择最佳定位策略）',
          '添加必要的等待和断言',
          '生成 Page Object 模型',
          '创建数据驱动测试参数'
        ]"
      />
    </div>
    
    <ProgressBar 
      :progress="progress"
      :status="progressStatus"
    />
    
    <div class="btn-container">
      <button class="btn" :disabled="!apiKey || isGenerating" @click="startGenerating">
        <i class="fas fa-play"></i> {{ isGenerating ? '生成中...' : '开始生成测试用例' }}
      </button>
      <button class="btn btn-outline" :disabled="!testCasesGenerated" @click="runTests">
        <i class="fas fa-bolt"></i> 执行测试
      </button>
    </div>
    
    <div class="console">
      <div class="console-header">
        <div class="console-title">DeepSeek AI 分析过程</div>
        <div><i class="fas fa-terminal"></i></div>
      </div>
      <div class="console-content">
        <div v-for="(line, index) in consoleOutput" :key="index" class="console-line">
          <span class="prompt">> </span>
          <span>{{ line }}</span>
        </div>
      </div>
    </div>
    
    <TestResults 
      :results="testResults"
      v-if="testResults.length > 0"
    />
  </div>
</template>

<script>
import ApiKeyInput from '../components/ApiKeyInput.vue'
import ProgressBar from '../components/ProgressBar.vue'
import TestCaseCard from '../components/TestCaseCard.vue'
import TestResults from '../components/TestResults.vue'

export default {
  name: 'PlaywrightPage',
  components: {
    ApiKeyInput,
    ProgressBar,
    TestCaseCard,
    TestResults
  },
  data() {
    return {
      apiKey: localStorage.getItem('deepseek-api-key') || '',
      searchQuery: '',
      progress: 0,
      progressStatus: '等待开始',
      isGenerating: false,
      testCasesGenerated: false,
      consoleOutput: [
        '请输入 DeepSeek API 密钥以开始'
      ],
      testResults: [],
      selectedFile: null,
      selectedFolder: null
    }
  },
  methods: {
    updateApiKey(key) {
      this.apiKey = key
    },
    saveApiKey() {
      localStorage.setItem('deepseek-api-key', this.apiKey)
      this.consoleOutput.push(`API 密钥已保存`)
    },
    searchTestCases() {
      if (this.searchQuery.trim()) {
        this.consoleOutput.push(`搜索测试用例: "${this.searchQuery}"`)
      }
    },
    handleFileSelect(event) {
      this.selectedFile = event.target.files[0];
      this.consoleOutput.push(`已选择文件: ${this.selectedFile.name}`);
    },
    handleFolderSelect(event) {
      this.selectedFolder = event.target;
      this.consoleOutput.push(`已选择文件夹，包含 ${this.selectedFolder.files.length} 个文件`);
    },
    startGenerating() {
      if (!this.apiKey) return
      
      this.isGenerating = true
      this.progressStatus = '分析页面结构中...'
      this.consoleOutput.push('开始分析目标页面结构...')
      
      // Simulate progress
      const interval = setInterval(() => {
        this.progress += Math.floor(Math.random() * 10) + 5
        if (this.progress >= 100) {
          this.progress = 100
          this.progressStatus = '完成'
          this.isGenerating = false
          this.testCasesGenerated = true
          this.consoleOutput.push('测试用例生成完成!')
          clearInterval(interval)
          
          // Generate sample test results
          this.generateTestResults()
        } else if (this.progress >= 70) {
          this.progressStatus = '生成测试脚本...'
        } else if (this.progress >= 30) {
          this.progressStatus = '生成测试用例...'
        }
      }, 500)
    },
    runTests() {
      if (!this.testCasesGenerated) return
      
      this.consoleOutput.push('开始执行测试用例...')
      
      // Simulate test execution
      setTimeout(() => {
        this.consoleOutput.push('测试执行完成!')
        this.consoleOutput.push('查看下方测试结果获取详细信息')
      }, 2000)
    },
    generateTestResults() {
      this.testResults = [
        {
          id: 1,
          title: '用户登录流程',
          status: 'passed',
          description: '验证用户可以使用有效凭据登录系统',
          details: '所有断言通过，登录流程正常'
        },
        {
          id: 2,
          title: '购物车添加商品',
          status: 'passed',
          description: '验证用户可以将商品添加到购物车',
          details: '商品成功添加到购物车，数量正确'
        },
        {
          id: 3,
          title: '结账流程',
          status: 'failed',
          description: '验证用户可以完成结账流程',
          details: '支付网关模拟响应超时 (5000ms)'
        },
        {
          id: 4,
          title: '移动端响应式布局',
          status: 'passed',
          description: '验证页面在移动设备上的显示',
          details: '所有元素在320px宽度下正确显示'
        },
        {
          id: 5,
          title: '表单验证',
          status: 'failed',
          description: '验证表单字段的客户端验证',
          details: '密码强度验证未触发'
        }
      ]
    }
  }
}
</script>

<style scoped>
.playwright-page .card-grid {
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
}

.playwright-page .subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  max-width: 700px;
  margin: 0 auto 30px;
  text-align: center;
}

.playwright-page .btn-container {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 30px 0;
}

.playwright-page .btn {
  background: linear-gradient(90deg, var(--secondary), var(--primary));
  color: #1a2a6c;
  border: none;
  padding: 12px 30px;
  font-size: 1.1rem;
  font-weight: 600;
  border-radius: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  gap: 10px;
}

.playwright-page .btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(0,0,0,0.3);
}

.playwright-page .btn:active {
  transform: translateY(1px);
}

.playwright-page .btn-outline {
  background: transparent;
  border: 2px solid var(--primary);
  color: var(--primary);
}

.playwright-page .progress-container {
  background: rgba(30, 30, 46, 0.8);
  border-radius: 15px;
  padding: 20px;
  margin: 30px 0;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.playwright-page .progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.playwright-page .progress-bar {
  height: 20px;
  background: #333;
  border-radius: 10px;
  overflow: hidden;
}

.playwright-page .progress-fill {
  height: 100%;
  background: linear-gradient(90deg, var(--secondary), var(--primary));
  width: 0%;
  transition: width 0.5s ease;
  border-radius: 10px;
}

.playwright-page .test-results {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 30px;
}

.playwright-page .test-case {
  background: rgba(30, 30, 46, 0.8);
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}

.playwright-page .test-case.passed {
  border-left: 4px solid var(--success);
}

.playwright-page .test-case.failed {
  border-left: 4px solid var(--danger);
}

.playwright-page .test-case h3 {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.playwright-page .test-case .status {
  padding: 3px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
}

.playwright-page .passed .status {
  background: rgba(146, 254, 157, 0.2);
  color: var(--success);
}

.playwright-page .failed .status {
  background: rgba(255, 107, 107, 0.2);
  color: var(--danger);
}

.playwright-page .api-key-container {
  background: rgba(30, 30, 46, 0.8);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 30px;
}

.playwright-page .api-key-input {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.playwright-page .api-key-input input {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid rgba(97, 218, 251, 0.3);
  background: rgba(30, 30, 46, 0.6);
  color: var(--text);
  font-family: 'Source Code Pro', monospace;
}

.playwright-page .console {
  background: #1e1e1e;
  border-radius: 15px;
  padding: 20px;
  margin-top: 30px;
  max-height: 400px;
  overflow-y: auto;
  box-shadow: inset 0 0 10px rgba(0,0,0,0.5);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.playwright-page .file-selection {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.playwright-page .file-input-container,
.playwright-page .folder-input-container {
  background: rgba(30, 30, 46, 0.8);
  border-radius: 15px;
  padding: 15px;
}

.playwright-page .file-input-container label,
.playwright-page .folder-input-container label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
}

.playwright-page .file-input {
  width: 100%;
  margin-bottom: 10px;
}

.playwright-page .file-name {
  font-size: 0.9rem;
  color: #aaa;
  display: block;
}
</style>